/* eslint-disable no-param-reassign */
/* eslint-disable vue/no-mutating-props */
import { CTX, getControlProvider, IViewProvider } from '@ibiz-template/runtime';
import { useNamespace } from '@ibiz-template/vue3-util';
import {
  defineComponent,
  h,
  inject,
  PropType,
  ref,
  resolveComponent,
} from 'vue';
import './control-shell.scss';
import { IControl } from '@ibiz/model-core';

export const IBizControlShell = defineComponent({
  name: 'IBizControlShell',
  props: {
    modelData: { type: Object as PropType<IControl>, required: true },
  },
  setup(props) {
    // 上下文里提前预告部件
    const ctx = inject('ctx') as CTX;

    ctx.evt.emit('onForecast', props.modelData.name!);

    const isComplete = ref(false);
    const errMsg = ref('');
    const provider = ref<IViewProvider>();
    getControlProvider(props.modelData)
      .then(item => {
        provider.value = item;
        isComplete.value = true;
        if (!item) {
          errMsg.value = `未找到对应部件的适配器`;
        }
      })
      .catch(err => {
        ibiz.log.error(err);
        errMsg.value = err.message;
        isComplete.value = true;
      });
    const ns = useNamespace('control-shell');

    return { ns, isComplete, errMsg, provider };
  },
  render() {
    if (this.isComplete && this.provider) {
      return h(
        resolveComponent(this.provider.component) as string,
        {
          ...this.$props,
          ...this.$attrs,
        },
        this.$slots,
      );
    }
    return (
      <div class={this.ns.b()} v-loading={!this.isComplete}>
        {this.isComplete ? this.errMsg : null}
      </div>
    );
  },
});
